package com.mike.blog.handler;

import com.mike.blog.dto.RequestDTO;
import com.mike.blog.dto.UserInfoDTO;
import com.mike.blog.service.TokenService;
import com.mike.blog.util.ContextHolder;
import com.mike.blog.util.CookieUtil;
import common.lib.core.annotation.NotNeedLogin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xiaozefeng
 * @date 12/12/18 11:44 PM
 */
@Slf4j
@Component
public class AuthHandler implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        NotNeedLogin annotation = handlerMethod.getMethod().getAnnotation(NotNeedLogin.class);
        if (annotation != null) {
            return true;
        }
        String token = CookieUtil.getCookie(request);
        UserInfoDTO userInfoDTO = tokenService.validate(token);
        if (userInfoDTO == null) {
            //throw new ServiceException(ResultEnum.INCORRECT_TOKEN);
            response.sendRedirect("/login");
            return false;
        }
        RequestDTO requestDTO = new RequestDTO(userInfoDTO);
        ContextHolder.set(requestDTO);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ContextHolder.remove();
    }
}
